import json

import paho.mqtt.client as mqtt
import ssl

# MQTT Broker 配置
from paho.mqtt.enums import CallbackAPIVersion


class MQTTClient:
    def __init__(self, broker, port, client_id, username, password):
        self.broker = broker
        self.port = port
        self.client_id = client_id
        self.username = username
        self.password = password

    def publish_message(self, topic, message):
        # 回调函数
        def on_connect(client, userdata, flags, reason_code, properties):
            if reason_code == 0:
                print(f"Connected to MQTT Broker with topic {topic}!")
                # 连接成功后立即发布消息
                client.publish(topic, json.dumps(message), qos=1)
            else:
                print(f"Failed to connect, reason code: {reason_code}")

        def on_publish(client, userdata, mid, reason_code, properties):
            print(f"Message Published to {topic}. Message ID: {mid}")
            # 消息发布后断开连接
            client.disconnect()

        # 创建MQTT客户端实例
        client = mqtt.Client(callback_api_version=CallbackAPIVersion.VERSION2, client_id=self.client_id)
        client.username_pw_set(self.username, self.password)

        # 设置回调函数
        client.on_connect = on_connect
        client.on_publish = on_publish

        # 启用SSL/TLS
        client.tls_set(cert_reqs=ssl.CERT_REQUIRED, tls_version=ssl.PROTOCOL_TLSv1_2)
        client.tls_insecure_set(True)  # 如果使用自签名证书，设置为True

        try:
            # 连接到MQTT Broker
            print(f"Connecting to MQTT Broker with topic {topic}...")
            client.connect(self.broker, self.port)

            # 运行网络循环
            client.loop_forever()

        except Exception as e:
            print(f"An error occurred: {e}")

        finally:
            print("Script execution completed")
